from PyQt5.QtCore import QThread, QDateTime, pyqtSignal
import requests
import cv2
import base64
import sqlite3

'''
检测线程类(继承QThread), 线程执行只会执行线程类中的run函数
'''


class detectThread(QThread):
    transmit_data = pyqtSignal(dict)    # 返回人脸信息
    search_data = pyqtSignal(str)   # 反馈学生签到情况
    sign_success = pyqtSignal(str)  # 签到是否成功
    flag = True

    def __init__(self, token, group_list):
        super(detectThread, self).__init__()
        self.access_token = token
        self.condition = False
        self.group_list = group_list

    # run函数执行结束，代表线程结束
    def run(self):
        self.db = sqlite3.connect("database.db")
        self.cursor = self.db.cursor()
        while self.flag:
            if self.condition:
                self.detect_data(self.base64_img)
                self.condition = False
        self.cursor.close()
        self.db.close()

    def get_base64(self, base64_image):
        # 当窗口产生信号，调用该槽函数，将传递数据存放在线程变量中
        self.base64_img = base64_image
        self.condition = True

    # 进行人脸检测
    def detect_data(self, base64_image):
        # 请求地址
        request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
        # 请求参数
        params = {
            "image": base64_image,
            "image_type": "BASE64",
            "face_field": "age,gender,glasses,face_type"
        }
        # 获取的access_token
        access_token = self.access_token
        # 合并的网络请求地址
        request_url = request_url + "?access_token=" + access_token
        # 通过json格式请求
        headers = {'content-type': 'application/json'}
        # 发送网络post请求，就会存在一定的返回结果等待时间，程序就会阻塞，存在一定的卡顿现象
        response = requests.post(request_url, data=params, headers=headers)
        if response:
            data = response.json()
            if data['error_code'] != 0:
                self.transmit_data.emit(dict(data))
                self.search_data.emit("NULL")
                return
            if data['result']['face_num'] > 0:
                self.face_search()
                # 产生信号
                self.transmit_data.emit(dict(data))

    # 人脸搜索
    def face_search(self):
        request_url = "https://aip.baidubce.com/rest/2.0/face/v3/search"
        string = self.group_list[0]
        for i in range(1, len(self.group_list)):
            string = string + ',' + self.group_list[i]
        params = {
            "image": self.base64_img,
            "image_type": "BASE64",
            "group_id_list": string,
        }
        access_token = self.access_token
        request_url = request_url + "?access_token=" + access_token
        headers = {'content-type': 'application/json'}
        response = requests.post(request_url, data=params, headers=headers)
        if response:
            message = response.json()
            if message['error_code'] == 0 and message['result']['user_list'][0]['score'] >= 90:
                data = message['result']['user_list'][0]
                user_id = data['user_id']
                group_id = data['group_id']
                name = data['user_info'].split(': ')[1]
                time = QDateTime.currentDateTime().toString("yyyy/MM/dd hh:mm:ss")
                temp = (user_id, group_id, name, time)
                if self.database_operations(temp):
                    self.search_data.emit(str(message['result']['user_list'][0]['user_info'] + '\n' + "班级: " + group_id + "\n签到成功！"))
                else:
                    self.search_data.emit(str(message['result']['user_list'][0]['user_info'] + '\n' + "班级: " + group_id + "\n已签到！"))


    def database_operations(self, temp):
        select_sql = "SELECT * FROM SIGNIN where user_id=? and group_id=?"
        value = self.cursor.execute(select_sql, (temp[0], temp[1]))
        if len(list(value)) == 0:
            self.cursor.execute("insert into SIGNIN values(?,?,?,?)", temp)
            self.db.commit()
            self.sign_success.emit("True")
            return True
        self.sign_success.emit("False")
        return False
